package svc

import (
	"context"
	"gozeroStandalone/internal/config"
	"gozeroStandalone/internal/model"
	"gozeroStandalone/internal/tools"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type ServiceContext struct {
	Config config.Config

	// 注入模型
	UserModel                 model.MallUserModel
	BannerModel               model.MallBannerModel
	OrderModel                model.MallOrderModel
	OrderItemModel            model.MallOrderItemModel
	OrderDeliveryAddressModel model.MallOrderDeliveryAddressModel
	OrderExpressModel         model.MallOrderExpressModel
	AccountModel              model.MallAccountModel
	AccountRoleModel          model.MallAccountRoleModel
	RoleModel                 model.MallRoleModel
	RoleAuthModel             model.MallRoleAuthModel
	AuthModel                 model.MallAuthModel
	DemoModel                 model.MallDemoModel

	// 注入日志器
	Logger logx.Logger
}

func NewServiceContext(c config.Config) *ServiceContext {
	svcCtx := &ServiceContext{
		Config: c,
		// 创建日志器
		Logger: logx.WithContext(context.Background()),
	}

	// ++++++++++++++ 获取mysql连接开始 ++++++++++++++
	mc := &tools.MysqlConfig{}
	datasource := ""

	// -------- 读取本地配置开始 --------
	// switch c.Env {
	// case "dev":
	// 	datasource = c.MysqlConf.Dev.DataSource
	// case "test":
	// 	datasource = c.MysqlConf.Test.DataSource
	// case "prod":
	// 	datasource = c.MysqlConf.Prod.DataSource
	// }
	// -------- 读取本地配置结束 --------

	// ------ 读取配置中心配置开始 ------
	cci, err := tools.GetSingleConfigCenterInstance(c)
	if err != nil {
		panic("读取配置中心mysql配置错误：" + err.Error())
	}

	// 获取配置中心数据
	cci.GetConfigCenter(c.ConfigCenterNameConf.MysqlConfigName, mc)
	datasource = mc.DataSource
	// ------ 读取配置中心配置结束 ------

	sc := sqlx.NewMysql(datasource)
	// ++++++++++++++ 获取mysql连接结束 ++++++++++++++

	// 创建模型
	svcCtx.AccountModel = model.NewMallAccountModel(sc)
	svcCtx.UserModel = model.NewMallUserModel(sc)
	svcCtx.BannerModel = model.NewMallBannerModel(sc)
	svcCtx.OrderModel = model.NewMallOrderModel(sc)
	svcCtx.OrderItemModel = model.NewMallOrderItemModel(sc)
	svcCtx.OrderDeliveryAddressModel = model.NewMallOrderDeliveryAddressModel(sc)
	svcCtx.OrderExpressModel = model.NewMallOrderExpressModel(sc)
	svcCtx.AccountRoleModel = model.NewMallAccountRoleModel(sc)
	svcCtx.RoleModel = model.NewMallRoleModel(sc)
	svcCtx.RoleAuthModel = model.NewMallRoleAuthModel(sc)
	svcCtx.AuthModel = model.NewMallAuthModel(sc)
	svcCtx.DemoModel = model.NewMallDemoModel(sc)

	return svcCtx
}
